'use client'

import { useEffect, useState } from 'react'
import { User, UserRole } from '@/types'

interface UserFormProps {
  user: User | null
  onClose: () => void
  onSave: (users: User[]) => void
}

export const UserForm: React.FC<UserFormProps> = ({ user, onClose, onSave }) => {
  const [username, setUsername] = useState('')
  const [role, setRole] = useState<UserRole>(UserRole.STAFF)
  const [name, setName] = useState('')
  const [password, setPassword] = useState('')

  useEffect(() => {
    if (user) {
      setUsername(user.username)
      setRole(user.role)
      setName(user.name)
      setPassword('')
    } else {
      setUsername('')
      setRole(UserRole.STAFF)
      setName('')
      setPassword('')
    }
  }, [user])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const method = user ? 'PUT' : 'POST'
    const url = user ? `/api/users/${user.id}` : '/api/users'

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, role, name, password }),
    })

    const updatedUser = await response.json()
    
    // 在添加或编辑用户后，调用 onSave 更新用户列表
    onSave(await fetch('/api/users').then(res => res.json())) // 直接获取最新的用户列表
    onClose()
  }

  const handleClear = () => {
    setUsername('')
    setRole(UserRole.STAFF)
    setName('')
    setPassword('')
  }

  return (
    <form onSubmit={handleSubmit} className="bg-white p-4 rounded shadow">
      <h2 className="text-lg font-semibold text-gray-800">{user ? '编辑用户' : '添加用户'}</h2>
      <div className="mt-2">
        <label className="block text-gray-700">姓名</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
          className="border border-gray-300 p-2 w-full rounded bg-gray-100 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>
      <div className="mt-2">
        <label className="block text-gray-700">用户名</label>
        <input
          type="text"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          required
          className="border border-gray-300 p-2 w-full rounded bg-gray-100 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>
      <div className="mt-2">
        <label className="block text-gray-700">密码</label>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
          className="border border-gray-300 p-2 w-full rounded bg-gray-100 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>
      <div className="mt-2">
        <label className="block text-gray-700">角色</label>
        <select
          value={role}
          onChange={(e) => setRole(e.target.value as UserRole)}
          className="border border-gray-300 p-2 w-full rounded bg-gray-100 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="ADMIN">管理员</option>
          <option value="MANAGER">经理</option>
          <option value="STAFF">员工</option>
        </select>
      </div>
      <button type="submit" className="mt-4 bg-blue-600 text-white p-2 rounded hover:bg-blue-700">
        {user ? '更新用户' : '添加用户'}
      </button>
      <button type="button" onClick={handleClear} className="mt-4 ml-2 bg-gray-300 p-2 rounded hover:bg-gray-400">
        清空
      </button>
    </form>
  )
} 